package com.zzr.demo.redis.service.impl;

import com.zzr.demo.redis.service.CounterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;

/**
 * @author: xiaomi
 * @date: 2021/10/7
 * @description:
 */
@Service("IDGeneratorService")
@Slf4j
public class IDGeneratorServiceImpl implements CounterService {

    final String ID_GE_KEY = "id::generator";
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    /**
     * 只是用一次
     *
     * @param value
     * @return
     */
    @Override
    public boolean init(int value) {
        ValueOperations<String, String> valueOperations = stringRedisTemplate.opsForValue();
        Boolean res = valueOperations.setIfAbsent(ID_GE_KEY, value + "");
        log.info("setNX:{}", res);
        return res;
    }

    @Override
    public long increase() {
        ValueOperations<String, String> valueOperations = stringRedisTemplate.opsForValue();
        Long increment = valueOperations.increment(ID_GE_KEY);
        return increment;
    }

    @Override
    public long increase(int num) {
        throw new NotImplementedException();
    }

    @Override
    public long decrease() {
        throw new NotImplementedException();
    }

    @Override
    public long decrease(int num) {
        throw new NotImplementedException();
    }
}
